package com.sikaryofficial.system.manager;

import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.common.core.constant.CacheConstants;
import com.sikaryofficial.common.core.utils.DateUtils;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.system.api.domain.SysUser;
import com.sikaryofficial.system.api.model.SysUserExtReq;
import com.sikaryofficial.system.api.util.NickNameGen;
import com.sikaryofficial.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;

import static com.sikaryofficial.common.core.constant.CacheConstants.USER_AVATAR_URL;

/**
 * @author : qinjinyuan
 * @desc : TODO  请填写你的功能描述
 * @date : 2024/03/02 21:08
 */
@Service
@Slf4j
public class UserAgeCacheManager {
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 获取用户信息缓存
     * @param userId
     * @return
     */
    public SysUser getSysUserInfoCacheById(Long userId) {
        return  redisService.getCacheMapValue(CacheConstants.USER_AVATAR_URL, userId.toString());
    }

    /**
     * 客户是否认证&框架合同期限
     * @param sysUserExtReq
     */
    public void updateCustomerCache(SysUserExtReq sysUserExtReq) {
        // 更新客户是否认证&框架合同期限
        String catchKey = CacheConstants.USER_AVATAR_URL;
        SysUser sysUser = redisService.getCacheMapValue(catchKey, sysUserExtReq.getUserId().toString());
        if (Objects.isNull(sysUser)) {
            // 查询数据库加载数据
            sysUser = sysUserMapper.selectUserById(sysUserExtReq.getUserId());
        }
        if(Objects.isNull(sysUser)){
            log.error("用户不存在");
            return;
        }
        sysUser.setFrameworkContractDuration(sysUserExtReq.getFrameworkContractDuration());
        sysUser.setHasValid(sysUserExtReq.isHasValid());
        sysUser.setFirstName(sysUserExtReq.getFirstName());
        sysUser.setLastName(sysUserExtReq.getLastName());
        sysUser.setCountry(sysUserExtReq.getCountry());
        sysUser.setEmail(sysUserExtReq.getEmail());
        sysUser.setPhonenumber(sysUserExtReq.getPhoneNumber());
        redisService.setCacheMapValue(catchKey, sysUserExtReq.getUserId().toString(), sysUser);
    }

    /**
     * @param userId
     */
    public void initUserCache(Long userId, SysUser sysUser) {
        // 设置年龄缓存
        if (Objects.isNull(sysUser)) {
            return;
        }
        redisService.setCacheMapValue(CacheConstants.USER_AVATAR_URL, userId.toString(), sysUser);
    }

    /**
     * @param userId
     */
    public void updateAvatarCache(Long userId, String avatar) {
        // 设置年龄缓存
        String catchKey = CacheConstants.USER_AVATAR_URL;
        SysUser sysUser = redisService.getCacheMapValue(catchKey, userId.toString());
        if (Objects.isNull(sysUser)) {
            sysUser = new SysUser(userId);
        }
        sysUser.setAvatar(avatar);
        redisService.setCacheMapValue(catchKey, userId.toString(), sysUser);
    }

    public void updateNickNameCache(Long userId, String nickName) {
        // 设置年龄缓存
        String catchKey = CacheConstants.USER_AVATAR_URL;
        SysUser sysUser = redisService.getCacheMapValue(catchKey, userId.toString());
        if (Objects.isNull(sysUser)) {
            sysUser = new SysUser(userId);
        }
        sysUser.setNickName(nickName);
        redisService.setCacheMapValue(catchKey, userId.toString(), sysUser);
    }

    public void updateBackImgCache(Long userId, String url) {
        // 设置年龄缓存
        String catchKey = CacheConstants.USER_AVATAR_URL;
        SysUser sysUser = redisService.getCacheMapValue(catchKey, userId.toString());
        if (Objects.isNull(sysUser)) {
            sysUser = new SysUser(userId);
        }
        sysUser.setBackImg(url);
        redisService.setCacheMapValue(catchKey, userId.toString(), sysUser);
    }

    /**
     * 更新年龄缓存
     * @param sysUser
     */
    public void updateUserAgeCache(SysUser sysUser) {
        // 设置年龄缓存
        String catchKey = MessageFormat.format(CacheConstants.USER_AGE_KEY, sysUser.getUserId().toString());
        if (Objects.nonNull(sysUser.getBirthDate())) {
            // 设置年龄缓存
            redisService.setCacheObject(catchKey, DateUtils.getAgeByBirthDate(sysUser.getBirthDate()));
        }
    }

    /**
     *
     * 系统启动，添加所有用户数据：缓存用户信息，用户年龄，用户头像地址等其他信息
     *
     */
    public void loadUserAgeData() {
        List<SysUser> sysUserList = sysUserMapper.selectAllUser();
        redisService.deleteObject(CacheConstants.USER_AGE_KEY);
        for (SysUser sysUser : sysUserList) {
            String catchKey = MessageFormat.format(CacheConstants.USER_AGE_KEY, sysUser.getUserId().toString());
            // 设置用户缓存 （账户名称，昵称，头像地址）
            redisService.setCacheMapValue(USER_AVATAR_URL, sysUser.getUserId().toString(), sysUser);
            if (Objects.isNull(sysUser.getBirthDate())) {
                continue;
            }
            // 设置年龄缓存
            redisService.setCacheObject(catchKey, DateUtils.getAgeByBirthDate(sysUser.getBirthDate()));
        }
    }

    public void updateNickName() {
        List<SysUser> sysUserList = sysUserMapper.selectAllUser();
        for (SysUser sysUser : sysUserList) {
            if (CharSequenceUtil.isNotBlank(sysUser.getNickName())) {
                continue;
            }
            if (CharSequenceUtil.isBlank(sysUser.getEmail())) {
                continue;
            }
            String nickName = "";
            try{
                nickName = NickNameGen.generateNicknameFromEmailPrefix(sysUser.getEmail());
            }catch (Exception e){
                log.error("nickname build error");
            }
            sysUserMapper.updateNickName(sysUser.getUserId(), nickName);
        }
    }


}
